package com.filebackup.struts.actions;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.filebackup.business.LocalFileService;
import com.filebackup.util.RootPathUtil;
import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("serial")
public class DownloadAction extends FilebackupSupport {
	
	private LocalFileService localFileService;
	
	private int id;

	public String getFileName() {
		return "you know it";
	}

	
	public String execute() throws Exception {
		String path=RootPathUtil.ROOT_PATH+this.getLocalFileService().findOwnerById(id).getName()+"\\"+localFileService.returnPath(id);
		
		FileInputStream res = new FileInputStream(
				path);
		int length=res.available();
		HttpServletResponse response=ServletActionContext.getResponse();
		response.setContentType("application/force-download");
		response.setHeader("Content-length", String.valueOf(length));
		response.setHeader("Content-Disposition", "attachment;filename=\""+this.getLocalFileService().findNameById(id)+ "\" ");
		OutputStream out=response.getOutputStream();
		int byteRead = 0;
		  byte[] buffer = new byte[512];
		  while((byteRead = res.read(buffer)) != -1) {
		   out.write(buffer, 0, byteRead);
		  }
		  res.close();
		  out.close();
		return null;
	}


	public void setId(int id) {
		this.id = id;
	}


	public int getId() {
		return id;
	}


	public void setLocalFileService(LocalFileService localFileService) {
		this.localFileService = localFileService;
	}


	public LocalFileService getLocalFileService() {
		return localFileService;
	}

}
